package tmc.logic.actionListeners;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import org.apache.log4j.Logger;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.gce.geotiff.GeoTiffWriter;
import org.geotools.geometry.jts.ReferencedEnvelope;

import tmc.gui.TMCFrame;

public class SaveFileActionListener implements ActionListener {

	private static Logger LOGGER = Logger.getLogger(SaveFileActionListener.class);

	final JFileChooser fc = new JFileChooser();
	TMCFrame parent;

	public SaveFileActionListener(TMCFrame frame) {
		parent = frame;
		fc.setFileFilter(new FileFilter() {

			@Override
			public String getDescription() {
				return "jpg, tiff and bmp files";
			}

			@Override
			public boolean accept(File f) {
				if (f != null && f.getName().contains(".") && f.isFile()) {
					String type = f.getName().split("\\.")[1];
					if (f.isFile()
							&& ("jpg".equalsIgnoreCase(type) || "bmp".equalsIgnoreCase(type) || "tiff"
									.equalsIgnoreCase(type))) {
						return true;
					}
				} else if (f.isDirectory()) {
					return true;
				}
				return false;
			}
		});
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
	}

	public void actionPerformed(ActionEvent event) {
		LOGGER.debug("Performing save file action.");
		LOGGER.debug("getting image width");

		try {
			String width = JOptionPane.showInputDialog(
					"Please type image width in pixels - height will be set automatically", "800");

			Integer numericWidth = Integer.parseInt(width);
			if (numericWidth == null) {
				JOptionPane.showMessageDialog(parent, "wrong nmber format");
				LOGGER.debug("input value is NaN");
				return;
			}
			LOGGER.debug("getting file name");

			File selectedFile;
			if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) {
				selectedFile = fc.getSelectedFile();
			} else {
				return;
			}

			LOGGER.debug("drawing image");
			Rectangle imageBounds = null;
			ReferencedEnvelope mapBounds = parent.getMap().getAreaOfInterest();

			double heightToWidth = mapBounds.getHeight() / mapBounds.getWidth();
			imageBounds = new Rectangle(0, 0, numericWidth, (int) Math.round(numericWidth * heightToWidth));

			BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB);

			Graphics2D gr = image.createGraphics();
			gr.setPaint(Color.WHITE);
			gr.fill(imageBounds);

			parent.getMapView().getRenderer().paint(gr, imageBounds, parent.getMap().getAreaOfInterest());

			String extension = null;

			if (selectedFile.getName().contains(".")) {
				extension = selectedFile.getName().split("\\.")[1];
			}
			if (extension == null) {
				extension = "jpg";
				selectedFile = new File(selectedFile.getAbsolutePath() + "." + extension);
			}
			if ("tiff".equalsIgnoreCase(extension) && parent.getMap().getCoordinateReferenceSystem() != null) {
				GridCoverageFactory gcf = new GridCoverageFactory();
				GridCoverage2D gc2d = gcf.create("TMCGeotiff", image, parent.getMap().getAreaOfInterest());
				GeoTiffWriter geoTiffWriter = new GeoTiffWriter(selectedFile);
				geoTiffWriter.write(gc2d, null);
			} else {
				ImageIO.write(image, extension, selectedFile);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			LOGGER.error("saving image file failed");
		}
	}
}
